package com.lw.leetcode.arr.b;

import com.lw.test.util.Utils;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 2435. 矩阵中和能被 K 整除的路径
 *
 * @author liw
 * @version 1.0
 * @date 2022/10/11 17:27
 */
public class NumberOfPaths {

    public static void main(String[] args) {
        NumberOfPaths test = new NumberOfPaths();

        int[][] arr = Utils.getArr(200, 250, 0, 100);
        int k = 50;
        System.out.println(k);

        int i = test.numberOfPaths(arr, k);
        System.out.println(i);
    }

    public int numberOfPaths(int[][] grid, int k) {
        int m = grid.length;
        int n = grid[0].length;
        int length = k * n;
        long[] arr = new long[length];
        int[] items = new int[k];
        int t = 0;
        for (int i = 0; i < n; i++) {
            t = (t + grid[0][i]) % k;
            arr[i * k + t] = 1;
        }
        for (int i = 1; i < m; i++) {
            Arrays.fill(items, 0);
            t = grid[i][0];
            int v = 0;
            while (v < k) {
                items[(v + t) % k] += arr[v];
                v++;
            }
            v = 0;
            while (v < k) {
                arr[v] = items[v];
                v++;
            }
            for (int j = 1; j < n; j++) {
                Arrays.fill(items, 0);
                t = grid[i][j];
                int st = j * k - k;
                v = 0;
                while (v < k) {
                    items[(v + t) % k] += arr[st + v];
                    v++;
                }
                st += k;
                v = 0;
                while (v < k) {
                    items[(v + t) % k] += arr[st + v];
                    v++;
                }
                v = 0;
                while (v < k) {
                    arr[st + v] = items[v] % 1000000007;
                    v++;
                }
            }
        }
        return (int) arr[n * k - k];
    }

}
